package com.tool.cn.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author wangzonghui
 * @date 2021-09-12 10:45:26
 * @Description cookies 工具类
 */
public final class CookieUtil {

	private static final Log log = LogFactory.getLog(CookieUtil.class);
	
	/**
	 * 添加cookies
	 * @param name 名字
	 * @param value 值
	 * @param maxSecond 存活时间
	 * @param response 
	 */
    public static void setCookie(String name, String value, int maxSecond, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxSecond);
//        cookie.setPath(Constant.LINE);
        response.addCookie(cookie);
        log.info("====== Set Cookie Over: Key=" + name + ",Value=" + value + ",MaxAge=" + maxSecond + "seconds");
    }
	
    public static String getCookie(String name, String defaultValue, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                	log.info("====== Get Cookie Over: Key=" + name + ",Value=" + cookie.getValue());
                    return cookie.getValue();
                }
            }
        }
        return defaultValue;
    }

    /**
     * 删除cookies
     * @param name
     * @param response
     */
    public static void removeCookie(String name, HttpServletResponse response) {
        setCookie(name, "value", 0, response);
    }
}
